package com.edu.whty.service.impl;


import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.UUIDUtils;
import com.edu.whty.dao.AttachFileDao;
import com.edu.whty.dao.DiskOwnerDao;
import com.edu.whty.dao.ResOwnerDao;
import com.edu.whty.dao.ResourceDao;
import com.edu.whty.entity.base.Pagination;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.capacity.CapacityUsed;
import com.edu.whty.entity.disk.DiskGrowthTrend;
import com.edu.whty.entity.disk.DiskOwner;
import com.edu.whty.entity.disk.FolderDTO;
import com.edu.whty.entity.disk.ResOwner;
import com.edu.whty.service.DiskService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @auther xiongxiaofei
 * @date 2016/11/14
 */
@Component("DiskService")
public class DiskServiceImpl implements DiskService {

	private Logger LOGGER = LogManager.getLogger(DiskServiceImpl.class);

	@Resource
	private ResourceDao resourceDao;

	@Resource
	private ResOwnerDao resOwnerDao;

	@Resource
	private DiskOwnerDao diskOwnerDao;

	@Resource
	private AttachFileDao attachFileDao;



	@Resource
	private JdbcTemplate jdbcTemplate;



	@Override
	public String createDiskOwnerResource(Map<String, Object> params) throws Exception {
		Object fid = params.get("fid");
		int diskType = Integer.parseInt(params.get("diskType").toString());
		String resId = UUIDUtils.getRandomUUID();
		DiskOwner diskOwner = new DiskOwner();
		if (fid != null) {
//			AttachFile attachFile = baseDAO.get("AttachFileMapper.selectOne", Long.valueOf(fid.toString()));
//            //慧教云-实体资源无附件需要重新获取同步到数据库中
//			if (attachFile == null && StringUtils.isBlank(isZj)) {
//           	 attachFile = new AttachFile();
//           	 String url = SysConf.getString("cos.cmsfile")+"/getAttachFileByFid/"+fid;
//    			 String response = new HttpClient(url).doGet();
//    			 if(StringUtils.isNotEmpty(response)) {
//    				JSONObject ob1 = JSONObject.fromObject(response);
//	   				if("000000".equals(ob1.optString("code"))) {
//	   					JSONObject ob = ob1.optJSONObject("data");
//	   					String fileMD5 = ob.optString("fileMd5");
//	   					String fileLength = ob.optString("fileLength");
//	   					String userId = ob.optString("userId");
//	   					String fileName = ob.optString("fileName");
//	   					String fileExt = ob.optString("fileExt");
//	   					attachFile.setFid(Long.valueOf(fid.toString()));
//	   					attachFile.setFileExt(fileExt);
//	   					attachFile.setFileId(UUIDUtils.getRandomUUID());
//	   					attachFile.setFileMd5(fileMD5);
//	   					attachFile.setFileLength(new Long(fileLength));
//	   					attachFile.setFileSize(FileUtils.size2string(new Long(fileLength)));
//	   					attachFile.setIsFileCenter(1);
//	   					attachFile.setUserId(userId);
//	   					attachFile.setPostedTime(new Date());
//	   					attachFile.setFileNameLocal(fileName);
//	   					attachFile.setFileNameRemote(fileName);
//	   					attachFile.setPostedPercent("100%");
//	   					attachFile.setIsDeleted("false");
//	   					attachFile.setPostComplete("true");
//	   					attachFile.setPostedLength(new Long(fileLength));
//	   					attachFileService.addAttachFile(attachFile);
//	   				}else{
//	   					throw new ServiceException("[fid=" + fid + "的文件在文件处理中不存在]");
//	   				}
//    			}else{
//    				throw new ServiceException("[fid=" + fid + "的文件在文件处理中不存在]");
//    			}
//            }
			// 创建资源
			com.edu.whty.entity.disk.Resource res = new com.edu.whty.entity.disk.Resource();
			res.setResId(resId);
			diskOwner.setResId(resId);
			res.setFid(Long.valueOf(fid.toString()));
			diskOwner.setFid(fid.toString());
			//根据fid获取资源的格式等信息
//			String getAttachUrl = SysConfig.getStrValue("upload_url")+"/getFileInfo/" + fid.toString();
//			LOGGER.info("请求查询福建信息地址url:"+getAttachUrl);
//			String resp = HttpClient.doGetMethod(getAttachUrl );
//			LOGGER.info("返回信息:"+resp);
			AttachFile attachFile = attachFileDao.selectOne(Long.valueOf(fid.toString()));
			if (attachFile != null) {

					diskOwner.setFileExt(attachFile.getFileExt());
					diskOwner.setFileLength(attachFile.getFileLength());
					diskOwner.setFileSize(attachFile.getFileSize());
					diskOwner.setFileMd5(attachFile.getFileMd5());
					DiskOwner diskOwner1 = diskOwnerDao.selectFormat(diskOwner);
					diskOwner.setFormatId(diskOwner1.getFormatId());

			}else {
				throw new Exception("附件信息查询失败");
			}


			if (diskType == 0) {
				res.setCreatorId(params.get("userId").toString());
				diskOwner.setCreatorId(params.get("userId").toString());
			}
			if (diskType == 1) {
				res.setCreatorId(params.get("groupId").toString());
				diskOwner.setCreatorId(params.get("groupId").toString());
			}
			Object title = params.get("title");
			if (title != null) {
				res.setTitle(title.toString());
				diskOwner.setTitle(title.toString());
			}

			Object resForm = params.get("resForm");
			if (resForm != null) {
				res.setResForm(resForm.toString());
				diskOwner.setResForm(resForm.toString());
			}

			Object url = params.get("url");
			if (url != null) {
				res.setUrl(url.toString());
				diskOwner.setUrl(url.toString());
			}
			res.setStatus("0");
			diskOwner.setStatus("0");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			res.setCreateTime(sdf.format(new Date()));
			diskOwner.setCreateTime(res.getCreateTime());
			diskOwner.setModifyTime(res.getCreateTime());
			diskOwner.setIsDelete("0");
//			resourceDao.insertOne(res);
//			//保存资源的资源类型关系
//			Object contentType = params.get("contentType");
//			if (contentType != null) {
//				if (contentType.toString().contains(",")) {
//					String[] types = contentType.toString().split(",");
//					for (String str : types) {
//						Map<String, String> map = new HashMap<String, String>();
//						map.put("RES_TYPE_ID", str);
//						map.put("RES_ID", res.getResId());
//						resTypeService.addResTypeRes(map);
//					}
//				} else {
//					Map<String, String> map = new HashMap<String, String>();
//					map.put("RES_TYPE_ID", contentType.toString());
//					map.put("RES_ID", res.getResId());
//					resTypeService.addResTypeRes(map);
//				}
//			}
//
//			//新增标签
//			List<String> tagIdList = CollectionUtils.newArrayList();
//			Object obj = params.get("tagNameList");
//			if (obj != null && obj instanceof ArrayList<?>) {
//				List<String> tagNameList = (List<String>) obj;
//				List<ResTag> tagList = new ArrayList<>();
//				List<ResTag> userTagList = new ArrayList<>();
//				for(String tagName : tagNameList){
//					String tagId = "";
//					String pkId = "";
//					ResTag tag = new ResTag();
//					if (StringUtils.isNotBlank(tagName)) {
//					    tagName = StringEscapeUtils.escapeHtml(tagName);
//						tagId = tagService.selectByName(tagName);
//					}
//					tag.setPkId(UUIDUtils.getRandomUUID());
//					tag.setTagName(tagName);
//					tag.setUserId(res.getCreatorId());
//					tag.setCreatorId(res.getCreatorId());
//					tag.setUserName(params.get("userName").toString());
//					tag.setCreateTime(new Date());
//					tag.setTargetType(0);
//					tag.setTargetId(res.getResId());
//					if(StringUtils.isBlank(tagId)){
//						tagId = UUIDUtils.getRandomUUID();
//						tag.setTagId(tagId);
//						tagList.add(tag);
//						userTagList.add(tag);
//					}else {
//						tag.setTagId(tagId);
//						userTagList.add(tag);
//					}
//				}
//				if(org.apache.commons.collections.CollectionUtils.isNotEmpty(tagList)){
//					tagService.insertTags(tagList);
//				}
//				if(org.apache.commons.collections.CollectionUtils.isNotEmpty(userTagList)){
//					tagService.insertUserTags(userTagList);
//				}
//			}
//
//			// 更新网盘大小
//			Map<String, Object> map = MapUtils.newHashMap();
//			map.put("uid", res.getCreatorId());
//			DishCapacity dish = dishCapacityDao.selectOne(map);
//			if (null != dish) {
//				Long usedCapacity = dish.getUsedCapacity() == null ? 0 : dish.getUsedCapacity();
//				Long fileSize = res.getFileLength() != null ? res.getFileLength() : 0l;
//				dish.setUsedCapacity(usedCapacity + fileSize);
//				DecimalFormat format = new DecimalFormat("#.0000");
//				String rate = format.format((usedCapacity + fileSize) / (float) dish.getMaxCapacity());
//				dish.setUsedRate(Float.parseFloat(rate));
//				dish.setModifyTime(new Date());
//				dishCapacityDao.updatefOne(dish);
//			}

			// 创建目录
			ResOwner resOwner = new ResOwner();
			resOwner.setDirId(UUIDUtils.getRandomUUID());
			diskOwner.setDirId(UUIDUtils.getRandomUUID());
			resOwner.setDirName(title.toString());
			diskOwner.setDirName(title.toString());
			resOwner.setResId(resId);


			Object parentCatalogId = params.get("parentCatalogId");
			if (parentCatalogId != null) {
				resOwner.setParentId(parentCatalogId.toString());
				diskOwner.setParentId(parentCatalogId.toString());
			}
			resOwner.setCreateTime(res.getCreateTime());
			resOwner.setStatus("0");
			resOwner.setIsFolder("1");
			diskOwner.setIsFolder("1");

			resOwner.setOwnerType(params.get("diskType").toString());
			if (diskType == 0) {// 个人网盘
				resOwner.setUserId(params.get("userId").toString());
				diskOwner.setUserId(params.get("userId").toString());
			}
			if (diskType == 1) {// 群组网盘
				resOwner.setGroupId(params.get("groupId").toString());
				diskOwner.setGroupId(params.get("groupId").toString());
			}

			Object resSource = params.get("resSource");
			if (resSource != null) {
				resOwner.setResSource(resSource.toString());
				diskOwner.setResSource(resSource.toString());
			}
//			diskOwner.setDownloadUrl(params.get("downloadUrl").toString());
//			diskOwner.setDiskFrom("2");
//			resOwnerDao.insertOne(resOwner);
			diskOwnerDao.insertOne(diskOwner);
//			//上传的资源同步到solr上
//			diskSolr.setContentId(resOwner.getDirId());
//			diskSolr.setIsFolder("1");
//			diskSolr.setResId(resId);
//			diskSolr.setType("1");// 资源上传
//			diskSolr.setUserId(params.get("userId").toString());
//			diskSolr.setUserName(params.get("userName").toString());
//			if (obj != null && obj instanceof ArrayList<?>) {
//				diskSolr.setTagNameList((List<String>) obj);
//				if (tagIdList.size() > 0) {
//					diskSolr.setTagIdList(tagIdList);
//				}
//			}
//			diskSolr.setTitle(title.toString());
//			diskSolr.setCreateTime(resOwner.getCreateTime());
//			if (url != null) {
//				diskSolr.setUrl(url.toString());
//			}
//
//			diskSolr.setFormat(res.getFormatId());
//			diskSolr.setFileExt(res.getFileExt());
//			diskSolr.setFileLength(res.getFileLength());
//			diskSolr.setFid(String.valueOf(res.getFid()));
//			diskSolr.setFileMd5(res.getFileMd5());
//			SolrHelper.addDiskSolr(diskSolr);
		}else {
			throw new Exception("fid为空");
		}
		return resId;
	}

	@Override
	public List<DiskOwner> queryDiskOwner(DiskOwner diskOwner) throws Exception {
		return diskOwnerDao.selectDiskOwnerList(diskOwner);
	}


	@Override
	public void removeResource(DiskOwner netdiskDTO) throws Exception {
		try {
			String dirIds = netdiskDTO.getDirId();
			List<String> dirIdList = Arrays.asList(dirIds.split(","));
			for(String dirId : dirIdList) {
				netdiskDTO.setDirId(dirId);
				List<DiskOwner> diskOwnerList = diskOwnerDao.selectDiskOwnerList(netdiskDTO);
				if (diskOwnerList.size() != 1) {
					throw new Exception("删除失败[资源不存在dirId=" + netdiskDTO.getDirId() + "]");
				}
				DiskOwner diskOwner = diskOwnerList.get(0);
				if (Constant.IS_FOLDER_YES.equals(diskOwner.getIsFolder())) { // 该资源是文件夹
					DiskOwner diskOwner1 = new DiskOwner();
					diskOwner1.setParentId(dirId);
					List<DiskOwner> diskOwnerCountList = diskOwnerDao.selectDiskOwnerList(diskOwner1);
					if (diskOwnerCountList.size() > 0) {
						throw new Exception("删除失败[该文件夹不为空]");
					}
				}
				diskOwner.setIsDelete("1");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateStr = sdf.format(new Date());
				diskOwner.setModifyTime(dateStr);
				diskOwnerDao.updateOne(diskOwner);
			}
		} catch(Exception ex) {
			throw new Exception(ex);
		}
	}

	@Override
	public void saveDiskOwnerBatch(List<DiskOwner> list) throws Exception {
		diskOwnerDao.saveDiskOwnerBatch(list);
	}

	@Override
	public DiskOwner getDiskOwner(String resId)  throws Exception{
		return diskOwnerDao.selectOne(resId);
	}

	@Override
	public String createFolder(FolderDTO folderDTO) throws Exception {
		try {
			if (folderDTO == null) {
				return null;
			}
			String ownerType = folderDTO.getOwnerType();
			if (StringUtils.isBlank(ownerType)) {
				throw new Exception("ownerType不能为空");
			}
			if (!Constant.OWNER_TYPE_PERSONAL.equals(ownerType) && !Constant.OWNER_TYPE_GROUP.equals(ownerType) && !Constant.OWNER_TYPE_ORG.equals(ownerType)) {
				throw new Exception("ownerType参数值错误");
			}

			String userId = folderDTO.getUserId();
			if (StringUtils.isBlank(userId)) {
				throw new Exception("userId不能为空");
			}

			String groupId = folderDTO.getGroupId();
			if (Constant.OWNER_TYPE_GROUP.equals(ownerType) && StringUtils.isBlank(groupId)) {
				throw new Exception("groupId不能为空");
			}

			String orgId = folderDTO.getOrgId();
			if (Constant.OWNER_TYPE_ORG.equals(ownerType) && StringUtils.isBlank(orgId)) {
				throw new Exception("orgId不能为空");
			}

			String resSource = StringUtils.isBlank(folderDTO.getResSource()) ? Constant.RES_SOURCE_DISK : folderDTO.getResSource();
			String resSourceName = Constant.resSourceMap.get(resSource);
			if (resSourceName == null) {
				throw new Exception("resSource参数值错误");
			}
			final DiskOwner netdisk = new DiskOwner();
			PropertyUtils.copyProperties(netdisk, folderDTO);
			netdisk.setIsDelete("0");
			List<DiskOwner> existList = diskOwnerDao.selectDiskOwnerList(netdisk);
			if (existList.size()>0) {
				throw new Exception("同名文件夹已经存在");
			}

			final String dirId = UUIDUtils.getRandomUUID();
			netdisk.setDirId(dirId);
			netdisk.setIsFolder(Constant.IS_FOLDER_YES);
			netdisk.setResSource(resSourceName);
			netdisk.setDirName(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(netdisk.getDirName()));
			netdisk.setTitle(netdisk.getDirName());
			netdisk.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			netdisk.setModifyTime(netdisk.getCreateTime());
			diskOwnerDao.insertOne(netdisk);
			return dirId;
		} catch(Exception ex) {
			throw new Exception(ex.getMessage());
		}
	}

	@Override
	public int selectDiskExists(String dirId) throws Exception {
		return diskOwnerDao.selectExists(dirId);
	}

	@Override
	public void batchUpdateDiskOwner(List<DiskOwner> list) throws Exception {
		 diskOwnerDao.updateBatch(list);
	}

	@Override
	public void renameFolder(FolderDTO folderDTO) throws Exception {
		try {
			DiskOwner netdisk = new DiskOwner();
			netdisk.setDirId(folderDTO.getDirId());
			netdisk.setDirName(folderDTO.getDirName());
			netdisk.setModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			diskOwnerDao.updateOne(netdisk);
		} catch (Exception ex) {
			throw new Exception(ex);
		}
	}

	@Override
	public void updateDiskOwner(DiskOwner diskOwner) throws Exception {
		diskOwnerDao.updateOne(diskOwner);
	}

	@Override
	public Long getOrgCapacity(String orgId) throws Exception {
		return diskOwnerDao.getOrgCapacity(orgId);
	}

	@Override
	public Long getUserCapacity(String userId) throws Exception {
		return diskOwnerDao.getUserCapacity(userId);
	}

	@Override
	public PageInfo selectUserCapacityListInPage(HashMap<String,Object> map, Pagination pagination) throws Exception {
		PageHelper.startPage(pagination.getCurPage(), pagination.getNumPerPage());

		List<CapacityUsed> list = diskOwnerDao.selectUserCapacityListInPage(map);

		PageInfo<CapacityUsed> pageInfo = new PageInfo<>(list);

		return pageInfo;
	}

	@Override
	public Long getCapacityByCondition(DiskOwner model) throws Exception {
		return diskOwnerDao.getCapacityByCondition(model);
	}

	@Override
	public List<DiskGrowthTrend> getGrowthTrendByDay(DiskOwner model) throws Exception {
		return diskOwnerDao.getGrowthTrendByDay(model);
	}

	@Override
	public List<DiskGrowthTrend> getGrowthTrendByWeek(DiskOwner model) throws Exception {
		return diskOwnerDao.getGrowthTrendByWeek(model);
	}

	@Override
	public List<DiskGrowthTrend> getGrowthTrendByHalfMonth(DiskOwner model) throws Exception {
		return diskOwnerDao.getGrowthTrendByHalfMonth(model);
	}

	@Override
	public List<DiskGrowthTrend> getGrowthTrendByMonth(DiskOwner model) throws Exception {
		return diskOwnerDao.getGrowthTrendByMonth(model);
	}

	@Override
	public void insert(DiskOwner diskOwner) throws Exception {
		diskOwnerDao.insertOne(diskOwner);
	}

}
